<template>
  <div class="home-container">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1>聊天室</h1>
          <div class="user-info">
            <span>欢迎，{{ authStore.user?.username }}</span>
            <el-button type="text" @click="handleLogout">退出</el-button>
          </div>
        </div>
      </el-header>

      <el-main class="main">
        <div class="content">
          <div class="sidebar">
            <div class="section">
              <h3>我的聊天室</h3>
              <el-button type="primary" @click="showCreateDialog = true" style="width: 100%; margin-bottom: 16px;">
                创建聊天室
              </el-button>

              <!-- 聊天室列表 -->
              <div class="room-list">
                <div v-for="room in myRooms" :key="room.id" class="room-item"
                  @click="handleRoomSelect(room.id.toString())">
                  <div class="room-info">
                    <h4>{{ room.name }}</h4>
                    <p>{{ room.description || '暂无描述' }}</p>
                    <small>{{ room._count?.users || 0 }}人 · {{ room._count?.messages || 0 }}条消息</small>
                  </div>
                  <el-tag v-if="room.userRole === 'owner'" type="success" size="small">房主</el-tag>
                </div>

                <!-- 空状态 -->
                <div v-if="myRooms.length === 0" class="empty-state">
                  <p>您还没有加入任何聊天室</p>
                  <p>点击上方按钮创建聊天室，或搜索加入其他聊天室</p>
                </div>
              </div>
            </div>

            <div class="section">
              <h3>搜索聊天室</h3>
              <el-input v-model="searchKeyword" placeholder="搜索聊天室..." prefix-icon="Search" @input="handleSearch"
                clearable />

              <div class="search-results">
                <div v-for="room in searchResults" :key="room.id" class="search-room-item"
                  @click="handleJoinRoom(room)">
                  <div class="room-info">
                    <h4>{{ room.name }}</h4>
                    <p>{{ room.description || '暂无描述' }}</p>
                    <small>{{ room._count?.users || 0 }}人 · {{ room._count?.messages || 0 }}条消息</small>
                  </div>
                  <el-button type="primary" size="small">加入</el-button>
                </div>

                <!-- 搜索结果空状态 -->
                <div v-if="searchKeyword && searchResults.length === 0" class="empty-state">
                  <p>没有找到匹配的聊天室</p>
                  <p>尝试使用其他关键词搜索</p>
                </div>
              </div>
            </div>
          </div>

          <div class="chat-area">
            <div class="welcome">
              <h2>欢迎来到聊天室</h2>
              <p>选择一个聊天室开始聊天，或者创建一个新的聊天室</p>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 创建聊天室对话框 -->
    <el-dialog v-model="showCreateDialog" title="创建聊天室" width="500px">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="聊天室名称">
          <el-input v-model="createForm.name" placeholder="请输入聊天室名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="createForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="createForm.isPublic" />
        </el-form-item>
        <el-form-item label="是否可搜索">
          <el-switch v-model="createForm.isSearchable" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="createForm.password" placeholder="可选，设置密码保护" />
        </el-form-item>
        <el-form-item label="最大人数">
          <el-input-number v-model="createForm.maxUsers" :min="1" :max="1000" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createChatRoom" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { chatroomAPI, messageAPI } from '@/services/api'

const router = useRouter()
const authStore = useAuthStore()

// 状态
const myRooms = ref([])
const searchResults = ref([])
const currentRoom = ref(null)
const messages = ref([])
const searchKeyword = ref('')
const newMessage = ref('')
const showCreateDialog = ref(false)
const creating = ref(false)
const messagesContainer = ref()

// 创建表单
const createForm = reactive({
  name: '',
  description: '',
  isPublic: true,
  isSearchable: true,
  password: '',
  maxUsers: 100
})

// 获取我的聊天室
async function fetchMyRooms() {
  try {
    const response = await chatroomAPI.getMyRooms()
    console.log('聊天室列表数据:', response.data)
    myRooms.value = response.data
  } catch (error) {
    console.error('获取聊天室失败:', error)
  }
}

// 搜索聊天室
async function handleSearch() {
  // if (!searchKeyword.value.trim()) {
  //   searchResults.value = []
  //   return
  // }

  try {
    const response = await chatroomAPI.searchRooms(searchKeyword.value)
    searchResults.value = response.data.chatRooms
  } catch (error) {
    // 静默处理错误
  }
}

// 选择聊天室
async function handleRoomSelect(roomId: string) {
  // 跳转到ChatView页面
  router.push(`/chat/${roomId}`)
}

// 加入聊天室
async function handleJoinRoom(room: any) {
  try {
    // 如果已经在 MyRooms 中，直接跳转到 ChatView
    if (myRooms.value.some((r: any) => r.id === room.id)) {
      router.push(`/chat/${room.id}`)
      return
    }
    await chatroomAPI.joinRoom(room.id.toString())
    ElMessage.success('成功加入聊天室')
    await fetchMyRooms()
    // 跳转到ChatView页面
    router.push(`/chat/${room.id}`)
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '加入失败')
  }
}

// 发送消息
async function sendMessage() {
  if (!newMessage.value.trim() || !currentRoom.value) return

  try {
    const response = await messageAPI.sendMessage(currentRoom.value.id.toString(), newMessage.value)

    messages.value.push(response.data)
    newMessage.value = ''

    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
  }
}

// 创建聊天室
async function createChatRoom() {
  if (!createForm.name.trim()) {
    ElMessage.error('请输入聊天室名称')
    return
  }

  creating.value = true
  try {
    await chatroomAPI.createRoom(createForm)
    ElMessage.success('创建成功')
    showCreateDialog.value = false
    await fetchMyRooms()

    // 重置表单
    Object.assign(createForm, {
      name: '',
      description: '',
      isPublic: true,
      isSearchable: true,
      password: '',
      maxUsers: 100
    })
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '创建失败')
  } finally {
    creating.value = false
  }
}

// 退出登录
async function handleLogout() {
  await authStore.logout()
  router.push('/login')
}

// 滚动到底部
function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
function formatTime(time: string) {
  return new Date(time).toLocaleString()
}

onMounted(() => {
  fetchMyRooms()
  handleSearch();
})
</script>

<style scoped>
.home-container {
  height: 100vh;
}

.header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  color: #409eff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.main {
  padding: 0;
  height: calc(100vh - 60px);
}

.content {
  display: flex;
  height: 100%;
}

.sidebar {
  width: 300px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  padding: 20px;
  overflow-y: auto;
}

.section {
  margin-bottom: 24px;
}

.section h3 {
  margin: 0 0 16px 0;
  color: #333;
}

.room-menu {
  border: none;
}

.room-list {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.room-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;
}

.room-item:last-child {
  border-bottom: none;
}

.room-item:hover {
  background: #f5f7fa;
}

.room-item.active {
  background: #e6f7ff;
  border-left: 3px solid #409eff;
}

.room-info {
  flex: 1;
  min-width: 0;
}

.room-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.room-info p {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.room-info small {
  font-size: 11px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state p {
  margin: 8px 0;
  font-size: 14px;
}

.search-results {
  margin-top: 16px;
}

.search-room-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.search-room-item:hover {
  border-color: #409eff;
  background: #f5f7fa;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.welcome {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  padding: 16px 20px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.chat-header h3 {
  margin: 0 0 4px 0;
}

.chat-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f5f7fa;
}

.message {
  display: flex;
  margin-bottom: 16px;
  gap: 12px;
}

.message.own-message {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
}

.message-header {
  margin-bottom: 4px;
}

.username {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.message-text {
  background: #fff;
  padding: 8px 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
}

.own-message .message-text {
  background: #409eff;
  color: #fff;
}

.chat-input {
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #e4e7ed;
}
</style>